package com.xjrh.traintravel.collector.netty.coder;

import com.xjrh.traintravel.collector.common.CodeConvertor;
import com.xjrh.traintravel.collector.netty.coder.command.AgreementConstant;
import com.xjrh.traintravel.collector.netty.coder.command.AgreementStructure;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * NettyServer接收到消息后使用的解码器
 *  <p>
 *      从ByteBuf中接收数据，还原为16进制字符串
 *  </p>
 *
 * @author snps
 * @create 2022-01-17 14:09
 * @describe
 **/
@Slf4j
public class AgreementDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        // 读入数据
        ByteBuf buf = in;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);

        // 读入的数据转换为16进制字符串
        String hexString = CodeConvertor.receiveBytes2HexString(bytes);
        // log.warn("收到的消息转16进制: {}", hexString);

        // 判断16进制字符串是否以"FEFEFEFE"开头
        if (!hexString.startsWith(AgreementConstant.PC_VALUE + AgreementConstant.SD_VALUE)) {
            log.error("不能识别的消息：前导 + 帧头，错误！" + hexString);
            return;
        }
        /*// 判断数据包长度--长度过小：长度过大，丢弃数据
        if (in.readableBytes() > AgreementConstant.BYTEBUF_IN_MAX_LENGTH) {
            in.skipBytes(in.readableBytes());
        }*/

        // 解码。16进制字符串 转为 结构体对象
        AgreementStructure agreement = Decoder.decode(hexString);
        out.add(agreement);
    }

}